﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using MyCompany.MyProject.Model;

namespace MyCompany.MyProject.WebApi.Filter;

/// <summary>
/// 控制器全局异常过滤器
/// </summary>
public class GlobalExceptionFilter : IExceptionFilter
{
    private readonly IWebHostEnvironment _env;
    private readonly ILogger<GlobalExceptionFilter> _logger;
    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="env"></param>
    /// <param name="logger"></param>
    public GlobalExceptionFilter(IWebHostEnvironment env,ILogger<GlobalExceptionFilter> logger)
    {
        _env = env;
        _logger = logger;
    }
    /// <summary>
    /// 异常处理方法
    /// </summary>
    /// <param name="context"></param>
    /// <exception cref="NotImplementedException"></exception>
    public void OnException(ExceptionContext context)
    {
        var json = new MessageModel<string>();
        json.msg = context.Exception.Message; // 返回错误消息
        json.success = false;
        json.status = 500;
        var errorAudit = "Unable to resolve service for";
        if(!string.IsNullOrEmpty(json.msg) && json.msg.Contains(errorAudit))
            json.msg = json.msg.Replace(errorAudit, $"（若新添加服务，需要重新编译项目）{errorAudit}");
        if (_env.IsDevelopment())
        {
            json.msgDev = context.Exception.StackTrace; // 返回堆栈信息
        }
        var res = new ContentResult();
        res.Content = Newtonsoft.Json.JsonConvert.SerializeObject(json);
        context.Result = res;
        // 记录异常日志
        _logger.LogError(json.msg+WriteLog(json.msg,context.Exception));
    }

    private string WriteLog(string throwMsg,Exception ex)
    {
        return string.Format("\r\n【自定义异常】{0}\r\n【异常类型】{1}\r\n【异常信息】{2}\r\n【堆栈调用】{3}\r\n【源】{4}\r\n",
            throwMsg, ex.GetType().Name, ex.Message, ex.StackTrace, ex.Source);
    }
}
